<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习平台</title>
    <style>
        body {
            display: grid;
            place-items: center;
            height: 100vh;
            height: 600px;
            margin: 0;
            align-content: center;
        }

        .centered-div {
            margin-top: 380px;
            width: 80%;
            height: 90px;
            background-color: rgba(182, 181, 184, 0);
            position: relative;
        }

        #input {
            border-radius: 5px;
            border: none;
            border-bottom: 2px solid #ccc;
            padding: 8px;
            font-size: 16px;
            width: calc(100% - 20px);
            position: absolute;
            bottom: 10px;
            left: 10px;
            box-sizing: border-box;
            outline: none;
            min-height: 24px;
            overflow: auto;
            border-bottom-color: #007BFF;
        }

        #content {
            display: flex;
            flex-direction: column-reverse;
            height: 30px;
            background-color: #69696900;
            margin-left: 12px;
            margin-right: 12px;
            padding-left: 8px;
            border-radius: 5px;
        }

        /* 新增按钮通用样式 */
        .action-button {
            position: fixed;
            right: 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background-color 0.3s;
        }

        .action-button:hover {
            background-color: #0056b3;
        }

        .action-button svg {
            width: 24px;
            height: 24px;
            fill: white;
        }

        /* 调整文件夹按钮位置 */
        .folder-button {
            bottom: 20px;
        }

        /* 字典按钮位置 */
        .dictionary-button {
            bottom: 80px;
        }

        .home-icon {
            position: fixed;
            right: 20px;
            bottom: 20px;
            background-color: #007BFF;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background-color 0.3s;
            padding: 0px 0px 0px 0px;
        }

        .home-icon svg {
            width: 20px;
            height: 20px;
            fill: white;
        }

        .home-icon:hover {
            background-color: #0056b3;
        }

        /* 新增选择按钮样式 */
        .selection-buttons {
            position: absolute;
            bottom: -40px; /* 调整按钮位置 */
            left: 10px;
            display: flex;
            gap: 10px;
        }

        #operation {
            list-style: none;
            margin-top: 0px;
            padding: 5px 5px 5px 5px;
            background-color: #f7f5f5;
                border-radius: 5px;
        }
        #operation li {
            /* margin-bottom: 10px; */
            float: left;
            margin-right: 12px;
            margin-left: 12px;
            background-color: #efefef;
            
        }
    </style>
</head>

<body>
    <iframe id="dictionaryIframe" src="https://smartisandict.youdao.com/" 
        style="
        width: 80vw; 
        height: 350px;
        position: absolute;
        top: 0px;
        left: calc(50% - 40vw);
        display: none;
        " 
        frameborder="0"></iframe>

    <div class="centered-div">
        <div id="content"></div>
        <div id="input" contenteditable="true" placeholder="请输入内容"></div>

    </div>
    <ul id="operation">
        <!-- 新增功能提示 -->
        <li >提示：按下[tab]键朗读</li>
        <li id="autoSpeak">
            <input type="checkbox" id="autoSpeakToggle" checked> 选中单词自动发音
        </li >
        <!-- 新增阅读开关 -->
        <li id="readToggleLi">
            <input type="checkbox" id="readToggle" checked> 开启阅读
        </li>
        <!-- 新增调速滚动条 -->
        <li>
            <label for="speedControl">语速: </label>
            <input type="range" id="speedControl" min="0.1" max="2" step="0.1" value="0.7">
            <span id="speedValue">0.7</span>
        </li>
    </ul>
    <!-- 字典 -->
    <div id="dictionaryButton" title="有道字典">
        <a class="home-icon" style="bottom: 80px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-book" viewBox="0 0 16 16">
                <path d="M1 2.828c.885-.37 2.154-.769 3.388-.893 1.33-.134 2.458.063 3.112.752v9.746c-.935-.53-2.12-.603-3.213-.493-1.18.12-2.37.461-3.287.811zm7.5-.141c.654-.689 1.782-.886 3.112-.752 1.234.124 2.503.523 3.388.893v9.923c-.918-.35-2.107-.692-3.287-.81-1.094-.111-2.278-.039-3.213.492zM8 1.783C7.015.936 5.587.81 4.287.94c-1.514.153-3.042.672-3.994 1.105A.5.5 0 0 0 0 2.5v11a.5.5 0 0 0 .707.455c.882-.4 2.303-.881 3.68-1.02 1.409-.142 2.59.087 3.223.877a.5.5 0 0 0 .78 0c.633-.79 1.814-1.019 3.222-.877 1.378.139 2.8.62 3.681 1.02A.5.5 0 0 0 16 13.5v-11a.5.5 0 0 0-.293-.455c-.952-.433-2.48-.952-3.994-1.105C10.413.809 8.985.936 8 1.783"/>
            </svg>
        </a>
    </div>

    <!-- 文件夹按钮 -->
    <div id="folderButton" title="共享文件管理">
        <a class="home-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                <path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V6h5.17l2 2H20v10z" fill="white"/>
            </svg>
        </a>
    </div>

    <script>
        var content = document.getElementById('content');
        var input = document.getElementById('input');
        var iframe = document.getElementById('dictionaryIframe');
        var centeredDiv = document.querySelector('.centered-div');
        // 获取文件夹按钮元素
        var folderButton = document.getElementById('folderButton');
        // 获取字典按钮元素
        var dictionaryButton = document.getElementById('dictionaryButton');
        // 用于追踪语音是否正在播放
        let isSpeaking = false; 
        // 初始化音频元素
        let audio = new Audio(); 
        // 获取阅读开关元素
        const readToggle = document.getElementById('readToggle');

        // 页面加载完成后请求 read 接口
        window.addEventListener('load', function () {
            fetch('/read')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    content.innerText = data.line;
                    // 根据开关状态和语言选择决定是否朗读
                    if (readToggle.checked) {
                        speak(data.line);
                    }
                })
                .catch(error => {
                    console.error('There has been a problem with your fetch operation:', error);
                });
        });

        input.onkeydown = function (event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                // 获取 content 内容并转换为首字母小写
                const contentText = content.innerText.trim();
                const contentTextLower = contentText.charAt(0).toLowerCase() + contentText.slice(1);
                // 获取 input 内容并转换为首字母小写
                const inputText = input.innerText.trim();
                const inputTextLower = inputText.charAt(0).toLowerCase() + inputText.slice(1);

                if (contentTextLower.startsWith(inputTextLower)) {
                    fetch('/read/next')
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            content.innerText = data.line;
                            // 根据开关状态和语言选择决定是否朗读
                            if (readToggle.checked) {
                                speak(data.line);
                            }
                            input.innerText = '';
                        })
                        .catch(error => {
                            console.error('There has been a problem with your fetch operation:', error);
                        });
                }
            }
            // 监听 Tab 键
            if (event.key === 'Tab') {
                event.preventDefault(); // 阻止默认的 Tab 行为
                if (readToggle.checked) {
                    speak(content.innerText);
                }
            }
        }

        input.onkeyup = function (event) {
            // 获取 content 内容并转换为首字母小写
            const contentText = content.innerText.trim();
            const contentTextLower = contentText.charAt(0).toLowerCase() + contentText.slice(1);
            // 获取 input 内容并转换为首字母小写
            const inputText = input.innerText.trim();
            const inputTextLower = inputText.charAt(0).toLowerCase() + inputText.slice(1);

            if (contentTextLower.startsWith(inputTextLower)) {
                input.style.borderBottomColor = "#007BFF";
            } else {
                input.style.borderBottomColor = "#FF0000";
            }
        }

        // 为文件夹按钮添加点击事件
        folderButton.addEventListener('click', function() {
            window.location.href = '/files';
        });

        // 为字典按钮添加点击事件
        dictionaryButton.addEventListener('click', function(event) {
            iframe.style.display = iframe.style.display === 'none' ? 'block' : 'none';
        });

        // 获取自动发音开关元素
        const autoSpeakToggle = document.getElementById('autoSpeakToggle');

        // 监听文本选中事件
        document.addEventListener('selectionchange', function() {
            const selection = window.getSelection();
            if (selection.rangeCount > 0) {
                const selectedText = selection.toString().trim();
                if (selectedText) {
                    // 有选中单词，打开 iframe 并更新 src
                    iframe.src = `https://smartisandict.youdao.com/dict?le=eng&q=${encodeURIComponent(selectedText)}`;
                    iframe.style.display = 'block';
                    // 检查开关状态，若开启则调用 /audit/word 接口并播放音频
                    if (autoSpeakToggle.checked) {
                        const audioUrl = `/audit/${encodeURIComponent(selectedText)}`;
                        audio.src = audioUrl;
                        audio.play().catch(error => {
                            console.error('播放音频失败:', error);
                        });
                    }
                } else {
                    // 取消选中，隐藏 iframe
                    iframe.style.display = 'none';
                }
            } else {
                // 取消选中，隐藏 iframe
                iframe.style.display = 'none';
            }
        });
        // 加载可用语音
        function loadVoices() {
            voices = speechSynthesis.getVoices();
        }

        // 获取调速滚动条元素
        const speedControl = document.getElementById('speedControl');
        const speedValue = document.getElementById('speedValue');

        // 初始化显示当前语速值
        speedValue.textContent = speedControl.value;

        // 监听调速滚动条变化
        speedControl.addEventListener('input', function() {
            speedValue.textContent = this.value;
        });

        // 页面加载时加载语音
        if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) {
            speechSynthesis.onvoiceschanged = loadVoices;
        }
        loadVoices();

        // 通用朗读函数
        function speak(text) {
            if (!'speechSynthesis' in window) {
                console.error('当前浏览器不支持语音合成功能');
                return;
            }
            console.log(text);
            if (isSpeaking) {
                // 若正在朗读，取消朗读
                speechSynthesis.cancel(); 
                isSpeaking = false;
            }
            const utterance = new SpeechSynthesisUtterance(text);
            // 判断文本是否主要为英语
            // const isEnglish = /^[a-zA-Z\s\.,!?]+$/.test(text);
            // const lang = isEnglish ? 'en-US' : 'zh-CN';
            utterance.lang = 'en-US';
            // 使用滚动条的值设置语速
            utterance.rate = parseFloat(speedControl.value); 
            // // 尝试设置对应语言的语音
            // const voice = voices.find(v => v.lang === lang);
            // if (voice) {
            //     utterance.voice = voice;
            // }
        
            // 当语音结束时更新状态
            utterance.onend = () => {
                isSpeaking = false;
            };
            speechSynthesis.speak(utterance);
            isSpeaking = true;
        }
    </script>
</body>

</html>

